/*
 * ZBrowser is an embeddable browser component.
 * Copyright (C) Author: Gangadhar Nagesh Metla (Novell, Inc.)
 * nmetla74@gmail.com 
 * Version 1.0
 * 1/3/2009
 * Filename NavigationUtils.java
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.novell.zenworks.agent.zbrowser;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.swing.JFrame;

import org.lobobrowser.gui.BrowserPanel;
import org.lobobrowser.ua.NavigationEvent;
import org.lobobrowser.ua.Parameter;
import org.lobobrowser.ua.RequestType;

import com.novell.zenworks.agent.common.Paths;
import com.novell.zenworks.agent.zbrowser.cmddialogs.InvokePropPageCmdDlg;
import com.novell.zenworks.agent.zbrowser.cmddialogs.PropPageCmdDialog;
import com.novell.zenworks.ipc.remoting.RemotingConstants;
import com.novell.zenworks.ipc.remoting.RemotingUtility;
import com.novell.zenworks.zicon.common.HTMLPage;
import com.novell.zenworks.zicon.common.IZenModuleServer;

public class NavigationUtils
{    
    public static void NavigateTo(NavigationEvent arg0, String resourcePath, HTMLPage page, BrowserPanel browserPanel, JFrame frame) throws Throwable
    {
        if (!arg0.getRequestType().equals(RequestType.PROGRAMMATIC))
        {            
            if (arg0.getURL().getAuthority().equalsIgnoreCase("zen")) //definition of zen should come from config param, NewPageORCommandCode="zen"
            {
                if (arg0.getURL() != null)
                {
                    // Route this to the correct handler
                    String pageId = arg0.getURL().getPath();
                    if (pageId.startsWith("/")) // Should always be true
                    {
                        pageId = pageId.substring(1);
                    }

                    if (pageId.contains("Framework"))
                    {
                        Map<String, String> data = parseQueryString(arg0.getURL().getQuery());
                        if ((data.containsKey("Cmd")) && (data.get("Cmd").equalsIgnoreCase("NewPage") && (data.containsKey("PageId"))))
                        {
                            if (page.getId().equalsIgnoreCase(data.get("PageId")))
                                return;

                            page.setId(data.get("PageId"));
                            ZURLStreamHandlerFactory factory = new ZURLStreamHandlerFactory(page);
                            URL url = new URL("http", "localhost", -1, resourcePath, factory.createURLStreamHandler("http"));
                            browserPanel.navigate(url);
                        }
                    } 
                    else if(pageId.contains("dataform"))
                    {
                        String query = getQuery(arg0);
                        getServer().doCDFSubmit(page.getId(), query);
                        Class cl = Class.forName("com.novell.zenworks.agent.zicon.PageApp");
                        Method mthd=cl.getMethod("nullifyDataform");
                        Integer output=(Integer)mthd.invoke(cl);
                        browserPanel.dispose();
                    }
                    else
                    {
                        String query = getQuery(arg0);
                        getServer().invokePropPageCommand(page.getId(), query);
                    }
                }
            }
            else if (arg0.getURL().getAuthority().equalsIgnoreCase("dlg"))
            {
                if (arg0.getURL() != null)
                {
                    String dlgId = arg0.getURL().getPath();
                    if (dlgId.startsWith("/")) //Should always be true
                    {
                        dlgId = dlgId.substring(1);
                    }

                    if (dlgId.contains("addRegKey"))
                    {
                        InvokePropPageCmdDlg cmdDlg = new InvokePropPageCmdDlg(frame);
                        cmdDlg.setTitle( ZBrowser.rm.getString("AddRegKeyTitle"));
                        cmdDlg.setBusyCaption( ZBrowser.rm.getString("AddRegKeyBusy"));
                        cmdDlg.setSuccessCaption(ZBrowser.rm.getString("AddRegKeySuccess"));
                        cmdDlg.setErrorCaption(ZBrowser.rm.getString("AddRegKeyFailed")); 
                        String pageId = dlgId.substring(dlgId.lastIndexOf('/') + 1);
                        String cmdData = getQuery(arg0);

                        cmdDlg.executeCommand(pageId, cmdData);
                    }
                    else if (dlgId.contains("winProxyMessage"))
                    {
                        String decodedURL = URLDecoder.decode(arg0.getURL().toString(),"UTF-8");
                        String message = "";
                        String taskName = "";
                        String status = "";
                        URI uri = new URI(arg0.getURL().toString());
                        
                        Map<String, String> collection = parseQueryString(uri.getQuery());
     
                        message = collection.get("message");
                        taskName = collection.get("taskName");
                        status = collection.get("status");
                        
                        if(status.equals("true"))
                        {
                            PropPageCmdDialog cmdDlg = new PropPageCmdDialog(frame,
                                    ZBrowser.rm.getString("Proxy_task_suceeded"),  
                                    taskName + ' ' + ZBrowser.rm.getString("Proxy_task_suceeded_title"), 
                                    PropPageCmdDialog.ERROR, message , true);
                            cmdDlg.setVisible(true);;
                        }
                        else
                        {
                            PropPageCmdDialog cmdDlg = new PropPageCmdDialog(frame,
                                    ZBrowser.rm.getString("Proxy_task_failed"),  
                                    taskName + ' ' + ZBrowser.rm.getString("Proxy_task_suceeded_title"), 
                                    PropPageCmdDialog.ERROR, message , true);
                            cmdDlg.setVisible(true);;
                        }
                    }
                    else if (dlgId.contains("showErrorMessage"))
                    {
                        String decodedURL = URLDecoder.decode(arg0.getURL().toString(),"UTF-8");
                        String errorMessage = "";
                        String policyName = "";
                        
                        URI uri = new URI(arg0.getURL().toString());
                        Map<String, String> collection = parseQueryString(uri.getQuery());

                        errorMessage = collection.get("arg");
                        policyName = collection.get("arg1");
                        PropPageCmdDialog cmdDlg = new PropPageCmdDialog(frame,ZBrowser.rm.getString("PolicyUIErrorDlgCaption"), policyName.trim() + ' ' + ZBrowser.rm.getString("PolicyUIErrorDlgTitle"), PropPageCmdDialog.ERROR, errorMessage , true);
                        cmdDlg.setVisible(true);
                    }                
                    else if (dlgId.contains("BundleManagement"))
                    {
                    	String itemID = null;
                    	if (arg0.getURL().getQuery() != null)
                    	{
                    		itemID = arg0.getURL().getQuery().substring(6);
                    	}

                    	//Novell.Zenworks.Zmd.AppUserModule.UserModuleEventHandler.Instance.ShowPropertiesDialogHandler(itemID);
                    	//Fix for Bug #473769. ZenNotifyIcon.exe must not have a direct reference to AppModule.dll and AppUserModule.dll.
                    	if(itemID != null)
                    	    getServer().invokePropPageCommand(page.getId(), "?PROPS="+itemID);
                    }
                }
            }

        }
        else //form cancellations etc.,
        {
            if (arg0.getURL().getAuthority().equalsIgnoreCase("zen")) //definition of zen should come from config param, NewPageORCommandCode="zen"
            {
                if (arg0.getURL() != null)
                {
                    // Route this to the correct handler
                    String pageId = arg0.getURL().getPath();
                    if (pageId.startsWith("/")) // Should always be true
                    {
                        pageId = pageId.substring(1);
                    }

                    if(pageId.contains("cancel"))
                    {
                        String query = "cancel=true";
                        getServer().doCDFSubmit(page.getId(), query);
                        Class cl = Class.forName("com.novell.zenworks.agent.zicon.PageApp");
                        Method mthd=cl.getMethod("nullifyDataform");
                        Integer output=(Integer)mthd.invoke(cl);
                        browserPanel.dispose();
                    } 
                }
            }

        }

    }

    public static Map<String, String> parseQueryString(String queryString)
    {
        Map<String, String> queryValues = new HashMap<String, String>();

        if (queryString != null && queryString.length() > 0)
        {
            if (queryString.startsWith("?"))
            {
                queryString = queryString.substring(1);
            }

            String[] pairs = queryString.split("&");
            for (int i = 0; i < pairs.length; i++)
            {
                String[] components = pairs[i].split("=");
                String key = components[0].replace('+', ' ');
                String value = (components.length == 0) ? "" : components[1].replace('+', ' ');
                queryValues.put(key, value);
            }
        }

        return queryValues;
    }

    public static IZenModuleServer getServer() throws RemoteException, NotBoundException
    {
         return (IZenModuleServer) RemotingUtility.getRemoteObject(RemotingConstants.ZICON_REMOTING_ID);
    }
    
    public static String getQuery(NavigationEvent arg0)
    {
        String query = "";
        if (arg0.getParamInfo() != null)
        {
            Parameter[] params = arg0.getParamInfo().getParameters();
            for (int i = 0; i < arg0.getParamInfo().getParameters().length; i++)
            {
                query += params[i].getName() + "=" + params[i].getTextValue() + "&";
            }

            query = query.substring(0, query.length() - 1);
        }
        else if(arg0.getURL() != null && arg0.getURL().getQuery() != null)
        {
        	query = arg0.getURL().getQuery();
        }
        
        return query;
    }

}
